<?php

/*
  Copyright (c) 2005 Kreditor AB
 
  Released under the GNU General Public License
*/

// INCLUDE THE LANGUAGE SUPPORT FILE
if(strpos($_SERVER['SCRIPT_FILENAME'],'admin'))
    @include_once '../'.DIR_WS_CLASSES . 'kreditor_lang.php';
else
    @include_once DIR_WS_CLASSES . 'kreditor_lang.php';

class pckreditor_de
{
    var $code, $title, $description, $enabled; 
    
    // class constructor
    function pckreditor_de()
    {

        global $order;

        $this->code = 'pckreditor_de';
        $this->title = MODULE_PAYMENT_PCKREDITOR_DE_TEXT_TITLE;
        $this->description = MODULE_PAYMENT_PCKREDITOR_DE_TEXT_DESCRIPTION;
	$this->enabled = ((MODULE_PAYMENT_PCKREDITOR_DE_STATUS == 'True' ||
                trim(MODULE_PAYMENT_PCKREDITOR_DE_PCLASS) == '' ||
                trim(MODULE_PAYMENT_PCKREDITOR_DE_MONTH) == '' ||
                trim(MODULE_PAYMENT_PCKREDITOR_DE_MONTH_FEE) == '' ||
                trim(MODULE_PAYMENT_PCKREDITOR_DE_RATE) == '' ||
                trim(MODULE_PAYMENT_PCKREDITOR_DE_START_FEE) == '') ?
            true : false);

        if (isset($order))
        {
            $currency = $order->info['currency'];

            if ($currency != "EU" && $currency != "eu" && $currency != "EUR" && $currency != "eur")
                $this->enabled = false;
			else
				$this->enabled = ($order->customer['country']['iso_code_2'] == "DE");
        } 

        if ($order->info['total'] > MODULE_PAYMENT_PCKREDITOR_DE_ORDER_LIMIT)
			$this->enabled = false;

        $this->sort_order = MODULE_PAYMENT_PCKREDITOR_DE_SORT_ORDER;

        if ((int)MODULE_PAYMENT_PCKREDITOR_DE_ORDER_STATUS_ID > 0)
			$this->order_status = MODULE_PAYMENT_PCKREDITOR_DE_ORDER_STATUS_ID;

        if (is_object($order))
            $this->update_status();

	} 
    
    // class methods
    function update_status()
    {
        global $order, $db;

        if ($this->enabled == true && (int)MODULE_PAYMENT_PCKREDITOR_DE_ZONE > 0) {
            $check_flag = false;

            $check = $db->Execute("select zone_id from " .
                TABLE_ZONES_TO_GEO_ZONES . " where geo_zone_id = '" .
                MODULE_PAYMENT_PCKREDITOR_DE_ZONE . "' and zone_country_id = '" . $order->billing['country']['id'] . "' order by zone_id");

            while (!$check->EOF) {
                if ($check->fields['zone_id'] < 1) {
                    $check_flag = true;
                    break;
                } elseif ($check->fields['zone_id'] == $order->billing['zone_id']) {
                    $check_flag = true;
                    break;
                } 
                $check->MoveNext();
            } 

            if ($check_flag == false) {
                $this->enabled = false;
            } 
        } 

    } 

    function javascript_validation()
    {
        return false;
    } 

    function selection()
    {
        require_once(DIR_WS_CLASSES . 'kreditor.php');
        global $order, $db, $currencies, $KRED_ISO3166_DE, $KRED_EUR;

		// xxx Disabled this payment method if we do not shop for more than 100 euro and doesnt have Klarna konto
		if ($order->info['subtotal']*$order->info['currency_value'] < 100 && (int)MODULE_PAYMENT_PCKREDITOR_DE_PCLASS_DEFAULT == 0)
			$this->enabled = false;

        $eid = MODULE_PAYMENT_PCKREDITOR_DE_EID;
        $secret = MODULE_PAYMENT_PCKREDITOR_DE_SECRET;

        $find_personnummer = $db->Execute("show columns from " . TABLE_CUSTOMERS);

        $has_personnummer = false;
        $has_dob = false;
        $has_ysalary = false;

        while (!$find_personnummer->EOF) {
            if ($find_personnummer->fields['Field'] == "customers_personnummer")
                $has_personnummer = true;
            if ($find_personnummer->fields['Field'] == "customers_dob")
                $has_dob = true;
            if ($find_personnummer->fields['Field'] == "customers_ysalary")
                $has_ysalary = true;
            $find_personnummer->MoveNext();
        } 

        if ($has_personnummer) {
            $customer = $db->Execute("select customers_personnummer from " .
                TABLE_CUSTOMERS . " where customers_id = '" .
                (int)$_SESSION['customer_id'] . "'"); 
            // $customer = zen_db_fetch_array($customer_query);
            $personnummer = $customer->fields['customers_personnummer'];
        } else if ($has_dob) {
            $customer = $db->Execute("select customers_dob from " .
                TABLE_CUSTOMERS . " where customers_id = '" .
                (int)$_SESSION['customer_id'] . "'"); 
            // $customer = zen_db_fetch_array($customer_query);
            $personnummer = substr($customer->fields['customers_dob'], 2);
        } else {
            $personnummer = "";
        } 

        if (MODULE_PAYMENT_PCKREDITOR_DE_PRE_POPULATE == "False") {
            $personnummer = "";
        } 

        if ($has_ysalary) {
            $customer = $db->Execute("select customers_ysalary from " .
                TABLE_CUSTOMERS . " where customers_id = '" .
                (int)$_SESSION['customer_id'] . "'");

            $ysalary = $customer->fields['customers_ysalary'];
        } 

		
	// Check if Klarna konto is active
	if(strlen(MODULE_PAYMENT_PCKREDITOR_DE_PCLASS_DEFAULT) > 0 && (int)MODULE_PAYMENT_PCKREDITOR_DE_PCLASS_DEFAULT != 0)
	{
		$pclass = MODULE_PAYMENT_PCKREDITOR_DE_PCLASS_DEFAULT;
		$months = "24";
		}
		
	
	if(strlen(MODULE_PAYMENT_PCKREDITOR_DE_PCLASS) > 0) {
		$pclass .= $months != "24" ? MODULE_PAYMENT_PCKREDITOR_DE_PCLASS : ";".MODULE_PAYMENT_PCKREDITOR_DE_PCLASS;
	}
	if(strlen(MODULE_PAYMENT_PCKREDITOR_DE_MONTH) > 0) {
		$months .= $months != "24" ? MODULE_PAYMENT_PCKREDITOR_DE_MONTH : ";".MODULE_PAYMENT_PCKREDITOR_DE_MONTH;
	}
	
		$pclassArr = array(
		"pclass" => explode(";", $pclass),
		"months" => explode(";", $months));

        $er = $order->info['currency_value'];
        $total = $order->info['total'] * 100 * $er;
		$pclasses .= "<br />";
		$kontoarray = array();
		$listitems = array();
		
		$default = "";
		$costpermonth = 0;
		
		
		for ($i = 0 ; $i < sizeof($pclassArr['pclass']); $i++)
		{
		
		if($pclassArr['pclass'][$i] == MODULE_PAYMENT_PCKREDITOR_DE_PCLASS_DEFAULT)
			{
			// Calculate the monthly cost
			monthly_cost($total, 1495, $months, 195, 0, $KRED_ISO3166_DE, $result);
			
			$costpermonth = $result;
			
			$pc = $currencies->format(ceil($result/100), false);
						
			$default = $pclassArr['pclass'][$i];	
			$kontoarray[] = array('id' => $pclassArr['pclass'][$i], 'text' => sprintf(KREDITOR_LANG_INFO_DE_KLARNA, $pc));
						
			$pclasses .= "&nbsp;&nbsp;" . sprintf(KREDITOR_LANG_INFO_DE_KLARNA, $pc) . "<br />";
			}
			else
			{
	  		$this->pc($eid, $total , $pclassArr['pclass'][$i], $KRED_ISO3166_DE, $flags, $secret, $result);
	  		$pc = $currencies->format(ceil($result / 100 / $er));

			if ($total >= 10000)
			{
								
				// xxx Check and see which alt. has the lowest monthly cost
					if($result < $costpermonth || $costpermonth == 0)
					{						
						$costpermonth = $result;
						$default = $pclassArr['pclass'][$i];
					}
		    	$pclasses .= "<br />".
		      	$listitems[] = array('text' => 
		      		KREDITOR_LANG_INFO_DE_PAYMENTTEXT1_PAY . $pc . 
		      		KREDITOR_LANG_INFO_DE_PAYMENTTEXT2_EACH . $pclassArr['months'][$i] . 
		      		KREDITOR_LANG_INFO_DE_PAYMENTTEXT3_MONTH,
				       'id' => $pclassArr['pclass'][$i]);
		    	$default = $pclassArr['pclass'][$i];
	  		}
			}
      	}
		
		if(isset($listitems))
		{
		// xxx Sort the items so that they will be presented 36 -> 24 and so on.
		sort($listitems, SORT_NUMERIC);
		}
		
		// xxx Check which arrays we should use to display the dropdown
		if(isset($listitems) && isset($kontoarray))
		// xxx Merge the array so that konto will be presented at the top
			$listarray = array_merge($kontoarray, $listitems);
		else if(isset($listitems))
			$listarray = $listitems;
		else
			$listarray = $kontoarray;
				
        			$addr_array = explode(" ", $order->billing['street_address']);
			if(sizeof($addr_array) > 1)
				$housenum = array_pop($addr_array);
			else
				$housenum = "";

    $fields = array(
                array('title' => KREDITOR_LANG_INFO_DE_IMGCONSUMERCREDIT,
			        'field' => ""),
		        array('title' => KREDITOR_LANG_INFO_DE_CHOOSECONSUMERCREDIT,
                    'field' => zen_draw_pull_down_menu('pckreditor_de_pclass', $listarray, $default)),
				array('title' => KREDITOR_LANG_INFO_DE_GENDER,
			    'field' => " Mann " . zen_draw_radio_field('pckreditor_de_gender',
				    '1') . " Frau " . zen_draw_radio_field('pckreditor_de_gender',
				    '0')),
		        array('title' => KREDITOR_LANG_INFO_DE_PERSONALNUMBER,
			        'field' => zen_draw_input_field('pckreditor_de_pnum',
					    $personnummer != "" ? strftime("%d%m%Y", strtotime($personnummer)) : "")),
                array('title' => KREDITOR_LANG_INFO_DE_FIRSTNAME,
                    'field' => zen_draw_input_field('pckreditor_de_fname',
                        $order->billing['firstname'])),
                array('title' => KREDITOR_LANG_INFO_DE_LASTNAME,
                    'field' => zen_draw_input_field('pckreditor_de_lname',
                        $order->billing['lastname'])),
				array('title' => KREDITOR_LANG_INFO_DE_STREETADDRESS,
			    'field' => zen_draw_input_field('pckreditor_de_street',
				    implode(" ", $addr_array),' size=\"15\"') . zen_draw_input_field('pckreditor_de_house',
				    $housenum, ' size=\"2\"')),
                array('title' => KREDITOR_LANG_INFO_DE_POSTCODE,
                    'field' => zen_draw_input_field('pckreditor_de_postno',
                        $order->billing['postcode'])),
                array('title' => KREDITOR_LANG_INFO_DE_CITY,
                    'field' => zen_draw_input_field('pckreditor_de_city',
                        $order->billing['city'])),
		    array('title' => KREDITOR_LANG_INFO_DE_PHONENUMBER2,
			    'field' => zen_draw_input_field('pckreditor_de_phone2',
			        $order->customer['telephone'])),
		        array('title' => KREDITOR_LANG_INFO_DE_PHONENUMBER,
			        'field' =>
			            zen_draw_input_field('pckreditor_de_phone',
					        $order->customer['telephone'])),
		        array('title' => KREDITOR_LANG_INFO_DE_EMAIL,
			        'field' =>
			            zen_draw_input_field('pckreditor_de_email',
					        $order->customer['email_address'])
			        ),
		            array('title' => KREDITOR_LANG_INFO_DE_ACCEPTCONDITION1_ACCEPT . " " . KREDITOR_LANG_INFO_DE_ACCEPTCONDITION3_CONDITIONS,
			            'field' => zen_draw_checkbox_field('pckreditor_de_check', '') . "<script type=\"text/javascript\" src=\"http://integration.klarna.com/js/klarnapart.js\"></script>
<script>
addKlarnaPartPaymentEvent(function() { InitKlarnaPartPaymentElements('klarna_partpayment'," . MODULE_PAYMENT_PCKREDITOR_DE_EID . ",'de', " . $total . "); });
</script>
<a href=\"#\" id=\"klarna_partpayment\" onclick=\"ShowKlarnaPartPaymentPopup();return false;\"></a>")); 

        return array('id' => $this->code,
            'module' => $this->title,
            'fields' => $fields);
            

    } 

    function pre_confirmation_check()
    {
        require_once(DIR_WS_CLASSES . 'kreditor.php');
        global $order, $GA_OLD, $PNO_FI;

        if ($_POST['pckreditor_de_check'] != "on") {
		$messageStack = new messageStack;
		$messageStack->add_session('checkout_payment', KREDITOR_LANG_INFO_DE_ERRORACCEPTCONDITION, 'error');
	zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT,
				   '',
				   'SSL', true, false));

        } 

        $pno = $this->pckreditor_de_pnum = $_POST['pckreditor_de_pnum'] . $_POST['pckreditor_de_gender'];
        $eid = MODULE_PAYMENT_PCKREDITOR_DE_EID;
        $secret = MODULE_PAYMENT_PCKREDITOR_DE_SECRET;

    	$this->pckreditor_de_fname = $_POST['pckreditor_de_fname'];
        $order->delivery['firstname'] = $this->pckreditor_de_fname;
        $order->billing['firstname'] = $this->pckreditor_de_fname;
        
    	$this->pckreditor_de_lname = $_POST['pckreditor_de_lname'];
        $order->delivery['lastname'] = $this->pckreditor_de_lname;
        $order->billing['lastname'] = $this->pckreditor_de_lname;
        
    	$this->pckreditor_de_street = $_POST['pckreditor_de_street'];
        $order->delivery['street_address'] = $this->pckreditor_de_street . " " . $_POST['pckreditor_de_house'];
        $order->billing['street_address'] = $this->pckreditor_de_street . " " . $_POST['pckreditor_de_house'];
        
		$this->pckreditor_de_housenum = $_POST['pckreditor_de_house'];
		
    	$this->pckreditor_de_postno = $_POST['pckreditor_de_postno'];
        $order->delivery['postcode'] = $this->pckreditor_de_postno;
        $order->billing['postcode'] = $this->pckreditor_de_postno;
        
    	$this->pckreditor_de_city = $_POST['pckreditor_de_city'];
        $order->delivery['city'] = $this->pckreditor_de_city;
        $order->billing['city'] = $this->pckreditor_de_city;
        
        $this->pckreditor_de_phone = $_POST['pckreditor_de_phone'];
        $order->delivery['telephone'] = $this->pckreditor_de_phone;
        $order->billing['telephone'] = $this->pckreditor_de_phone;
        
		$this->pckreditor_de_phone2 = $_POST['pckreditor_de_phone2'];
		
        $this->pckreditor_de_email = $_POST['pckreditor_de_email'];
        $order->delivery['email_address'] = $this->pckreditor_de_email;
        $order->billing['email_address'] = $this->pckreditor_de_email;

        $this->pckreditor_de_pclass = $_POST['pckreditor_de_pclass'];
        
    } 

    function confirmation()
    {
        return array('title' => MODULE_PAYMENT_PCKREDITOR_DE_TEXT_CONFIRM_DESCRIPTION);
    } 

    function process_button()
    {
        global $order, $order_total_modules, $pckreditor_de_ot;
        $counter = 1;
        $a = count($this->addrs);
        $process_button_string = "";
        if ($a > 1) {
            $process_button_string .= "<div align='left'>";
            $process_button_string .= "<table border='0' width='100%' cellspacing='1' cellpadding='2' class='infoBox'>";
            $process_button_string .= "<tr><td class='main'><b>".KREDITOR_LANG_INFO_DE_CHOOSEALTERNATIVES."</b></td></tr>";
            $process_button_string .= "<tr class='infoBoxContents'><td>";

            foreach ($this->addrs as $addr) {
                $this->pckreditor_de_fname = $addr[0];
                $this->pckreditor_de_lname = $addr[1];
                $this->pckreditor_de_street = $addr[2];
                $this->pckreditor_de_postno = $addr[3];
                $this->pckreditor_de_city = $addr[4];

                if ($counter == 1) {
                    $checked = true;
                } else {
                    $checked = false;
                } 

                $process_button_string .=
                zen_draw_radio_field('addr_num', $counter, $checked, '') .
                zen_draw_hidden_field('pckreditor_de_pclass' . $counter,
                    $this->pckreditor_de_pclass) .
                zen_draw_hidden_field('pckreditor_de_pnum' . $counter,
                    $this->pckreditor_de_pnum) .
                zen_draw_hidden_field('pckreditor_de_fname' . $counter,
                    $this->pckreditor_de_fname) .
                zen_draw_hidden_field('pckreditor_de_lname' . $counter,
                    $this->pckreditor_de_lname) .
                zen_draw_hidden_field('pckreditor_de_street' . $counter,
                    $this->pckreditor_de_street) . $this->pckreditor_de_street . " " .
				zen_draw_hidden_field('pckreditor_de_house' . $counter,
                    $this->pckreditor_de_housenum).
				zen_draw_hidden_field('pckreditor_de_postno' . $counter,
                    $this->pckreditor_de_postno) . $this->pckreditor_de_postno . " " .
                zen_draw_hidden_field('pckreditor_de_city' . $counter,
                    $this->pckreditor_de_city) . $this->pckreditor_de_city . " " .
                zen_draw_hidden_field('pckreditor_de_phone' . $counter,
                    $this->pckreditor_de_phone) .
				zen_draw_hidden_field('pckreditor_de_phone2' . $counter,
                    $this->pckreditor_de_phone2) .
                zen_draw_hidden_field('pckreditor_de_email' . $counter,
                    $this->pckreditor_de_email) . "<br/>";
                $counter++;
            } 
            $process_button_string .= "</td></tr></table><br/></div>";
        } else {
            $process_button_string .=
            zen_draw_hidden_field('addr_num', $counter, $checked, '') .
            zen_draw_hidden_field('pckreditor_de_pclass' . $counter, $this->pckreditor_de_pclass) .
            zen_draw_hidden_field('pckreditor_de_pnum' . $counter, $this->pckreditor_de_pnum) .
            zen_draw_hidden_field('pckreditor_de_fname' . $counter, $this->pckreditor_de_fname) .
            zen_draw_hidden_field('pckreditor_de_lname' . $counter, $this->pckreditor_de_lname) .
            zen_draw_hidden_field('pckreditor_de_street' . $counter,
                $this->pckreditor_de_street) .
			zen_draw_hidden_field('pckreditor_de_house' . $counter,
                    $this->pckreditor_de_housenum).
            zen_draw_hidden_field('pckreditor_de_postno' . $counter,
                $this->pckreditor_de_postno) .
            zen_draw_hidden_field('pckreditor_de_city' . $counter, $this->pckreditor_de_city) .
            zen_draw_hidden_field('pckreditor_de_phone' . $counter, $this->pckreditor_de_phone) .
			zen_draw_hidden_field('pckreditor_de_phone2' . $counter,
                    $this->pckreditor_de_phone2) .
            zen_draw_hidden_field('pckreditor_de_email' . $counter, $this->pckreditor_de_email);
        } 

        $process_button_string .= zen_draw_hidden_field(zen_session_name(),
            zen_session_id());
        
        return $process_button_string;
    } 

    function before_process()
    {
        global $order, $currencies, $pckreditor_de_ot;

        require_once(DIR_WS_CLASSES . 'kreditor.php');

        $eid = MODULE_PAYMENT_PCKREDITOR_DE_EID;
        $estoreUser = $_SESSION['customer_id'];
        $goodsList = array();
        $n = sizeof($order->products); 
        // First all the ordinary items
        for ($i = 0 ; $i < $n ; $i++) {
            $price_with_tax = $order->products[$i]['final_price'] * $order->info['currency_value']*($order->products[$i]['tax']/100+1) * 100;
            $attributes = "";

            if (isset($order->products[$i]['attributes'])) {
                foreach($order->products[$i]['attributes'] as $attr) {
                    $attributes = $attributes . ", " . $attr['option'] . ": " . $attr['value'];
                } 
            } 

            if (MODULE_PAYMENT_PCKREDITOR_DE_ARTNO == 'id' ||
                MODULE_PAYMENT_PCKREDITOR_DE_ARTNO == '') {
                $goodsList[] =
                mk_goods_flags($order->products[$i]['qty'],
                    zen_get_prid($order->products[$i]['id']),
                    strip_tags($order->products[$i]['name'] . $attributes),
                    $price_with_tax,
                    $order->products[$i]['tax'],
                    0, 32);
            } else {
                $goodsList[] =
                mk_goods_flags($order->products[$i]['qty'],
                    $order->products[$i][MODULE_PAYMENT_PCKREDITOR_DE_ARTNO],
                    strip_tags($order->products[$i]['name'] . $attributes),
                    $price_with_tax,
                    $order->products[$i]['tax'],
                    0, 32);
            } 
        } 

        
		// Then the extra charges like discount, invoicefee and shipping.
		foreach($GLOBALS['order_totals'] as $k_global => $v_global)
		{
		
			if(is_int(strpos(strtolower($v_global['code']),'discount')) || is_int(strpos(strtolower($v_global['title']),'discount'))
				|| is_int(strpos(strtolower($v_global['code']),'coupon')) || is_int(strpos(strtolower($v_global['title']),'coupon')))
			{
				$tod_rate = zen_get_tax_rate(MODULE_PAYMENT_PCKREDITOR_DE_TAX_CLASS);
				$name = strip_tags($v_global['title']);
				$value = -$v_global['value'];
				$tax = $tod_rate*1;
				$name = str_replace(":", "", $name);
				$price_without_tax = $value*$order->info['currency_value']*100;
				if (DISPLAY_PRICE_WITH_TAX == 'true') {
					$price_without_tax = ($price_without_tax/(1+$tax/100));
				}
				if ($value != "" && $value != 0) 
					$goodsList[] = mk_goods(1, "",
								$name,
								$price_without_tax, $tax, 0);
			}
			
			if(is_int(strpos(strtolower($v_global['code']),'charge')) || is_int(strpos(strtolower($v_global['title']),'charge'))
				|| is_int(strpos(strtolower($v_global['code']),'payment')) || is_int(strpos(strtolower($v_global['title']),'payment'))
				|| is_int(strpos(strtolower($v_global['code']),'fee')) || is_int(strpos(strtolower($v_global['title']),'fee')))
			{
				$tod_rate = zen_get_tax_rate(MODULE_PAYMENT_PCKREDITOR_DE_TAX_CLASS);
				$name = strip_tags($v_global['title']);
				$value = $v_global['value'];
				$tax = $tod_rate*1;                        
				$name = str_replace(":", "", $name);
				$price_without_tax = $value*$order->info['currency_value']*100;
				if (DISPLAY_PRICE_WITH_TAX == 'true') {
					$price_without_tax = ($price_without_tax/(1+$tax/100));
				}
				if ($value != "" && $value != 0) 
					$goodsList[] = mk_goods(1, "",
								$name,
								$price_without_tax, $tax, 0);
			}
		}
		 

        if (zen_not_null($order->info['shipping_method'])) {
            $price_without_tax = $order->info['shipping_cost'] * $order->info['currency_value'] * 100;
            $tod_rate = zen_get_tax_rate(MODULE_PAYMENT_PCKREDITOR_DE_TAX_CLASS);
            $tax = $tod_rate * 1;

			if (DISPLAY_PRICE_WITH_TAX == 'false') {
				$price_without_tax = ($price_without_tax*(1+$tax/100));
			}
				$goodsList[] = mk_goods_flags(1, "",
							$order->info['shipping_method'],
							$price_without_tax, $tax, 0, 40);
        } 

        $secret = MODULE_PAYMENT_PCKREDITOR_DE_SECRET;
        $estoreOrderNo = "";
        $shipmentfee = 0;
        $shipmenttype = 1;
        $handlingfee = 0;
        $ready_date = ""; 
        // Fixes potential security problem
        $addr_num = $_POST['addr_num'];
        $order->delivery['firstname'] = $_POST['pckreditor_de_fname' . $addr_num];
        $order->billing['firstname'] = $_POST['pckreditor_de_fname' . $addr_num];
        $order->delivery['lastname'] = $_POST['pckreditor_de_lname' . $addr_num];
        $order->billing['lastname'] = $_POST['pckreditor_de_lname' . $addr_num];
        $order->delivery['street_address'] = $_POST['pckreditor_de_street' . $addr_num];
        $order->billing['street_address'] = $_POST['pckreditor_de_street' . $addr_num];
        $order->delivery['postcode'] = $_POST['pckreditor_de_postno' . $addr_num];
        $order->billing['postcode'] = $_POST['pckreditor_de_postno' . $addr_num];
        $order->delivery['city'] = $_POST['pckreditor_de_city' . $addr_num];
        $order->billing['city'] = $_POST['pckreditor_de_city' . $addr_num];
        $order->delivery['telephone'] = $_POST['pckreditor_de_phone' . $addr_num];
        $order->billing['telephone'] = $_POST['pckreditor_de_phone' . $addr_num];
        $order->delivery['email_address'] = $_POST['pckreditor_de_email' . $addr_num];
        $order->billing['email_address'] = $_POST['pckreditor_de_email' . $addr_num];
        $pno = $_POST['pckreditor_de_pnum' . $addr_num];
        $fname = $_POST['pckreditor_de_fname' . $addr_num];
        $lname = $_POST['pckreditor_de_lname' . $addr_num];
        $addr = mk_addr_de("", $_POST['pckreditor_de_street' . $addr_num],
            $_POST['pckreditor_de_postno' . $addr_num],
            $_POST['pckreditor_de_city' . $addr_num],
            $_POST['pckreditor_de_phone2' . $addr_num],
            $_POST['pckreditor_de_phone' . $addr_num], 
		$_POST['pckreditor_de_email' . $addr_num], $_POST['pckreditor_de_house' . $addr_num]);
        $passwd = "";
        $clientIp = $_SERVER["REMOTE_ADDR"];
        $newPasswd = "";
        $pno = str_replace("-", "", $pno);
        $pno = str_replace(" ", "", $pno);

        if (MODULE_PAYMENT_PCKREDITOR_DE_AUTO_ACTIVATE == 'True') {
            $flags = $AUTO_ACTIVATE ;
            if (MODULE_PAYMENT_PCKREDITOR_DE_AUTO_ACTIVATE_SEND_DELAY > 0) {
                $ready_date =
                date('Y-m-d',
                    strtotime('now +' .
                        MODULE_PAYMENT_PCKREDITOR_DE_AUTO_ACTIVATE_SEND_DELAY . ' days'));
            } 
        } else
            $flags = 0;

        $pclass = $_POST['pckreditor_de_pclass' . $addr_num];
        $ysalary = "";

        $status = add_transaction_de($eid, $estoreUser, $secret, $estoreOrderNo,
            $goodsList, $shipmentfee, $shipmenttype,
            $handlingfee, $pno, $fname, $lname, $addr,
            $passwd, $clientIp, $newPasswd, $flags,
            $comment, $ready_date, "", $pclass, $ysalary, $result);

        if ($status == 0) {
            $order->kreditorref = $result;
            $payment['tan'] = $result;
        } else {
$messageStack = new messageStack;
		$messageStack->add_session('checkout_payment', $result, 'error');
	zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT,
				   '',
				   'SSL', true, false));
        } 
    } 

    function after_process()
    {
        global $insert_id, $order, $db;

        $find_st_optional_field_query = $db->Execute("show columns from " . TABLE_ORDERS);

        $has_kreditor_ref = false;

        while (!$find_st_optional_field_query->EOF) {
            if ($find_st_optional_field_query->fields['Field'] == "kreditorref")
                $has_kreditor_ref = true;
            $find_st_optional_field_query->MoveNext();
        } 

        if ($has_kreditor_ref) {
            $db->Execute("update " . TABLE_ORDERS . " set kreditorref='" . $order->kreditorref . "' " . " where orders_id = '" . $insert_id . "'");
        } 
        // Insert transaction # into history file
        $sql_data_array = array('orders_id' => $insert_id,
            'orders_status_id' =>
            ($order->info['order_status']),
            'date_added' => 'now()',
            'customer_notified' => 0,
            'comments' => ('Accepted by Klarna ' .
                date("Y-m-d G:i:s") . ' Invoice #: ' . $order->kreditorref));

        zen_db_perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);
        $secret = MODULE_PAYMENT_PCKREDITOR_DE_SECRET;
        $eid = MODULE_PAYMENT_PCKREDITOR_DE_EID;
        $invno = $order->kreditorref;
        update_orderno($eid, $invno, $secret, utf8_decode($insert_id), $result);
        return false;
    } 

    function get_error()
    {
        if (isset($_GET['message']) &&
                strlen($_GET['message']) > 0) {
            $error = stripslashes(urldecode($_GET['message']));
        } else {
            $error = $_GET['error'];
        } 
        return array('title' => KREDITOR_LANG_INFO_DE_ERRORDIVIDE,
            'error' => $error);
    } 

    function check()
    {
        global $db;

        if (!isset($this->_check)) {
            $check_query = $db->Execute("select configuration_value from " .
                TABLE_CONFIGURATION . " where configuration_key = " . "'MODULE_PAYMENT_PCKREDITOR_DE_STATUS'");
            $this->_check = $check_query->RecordCount();
        } 
        return $this->_check;
    } 

    function pc($eid, $sum, $pclass, $country, $flags, $secret, &$result)
    {
        $pclassArr = array('pclass' => explode(";", MODULE_PAYMENT_PCKREDITOR_DE_PCLASS),
            'months' => explode(";", MODULE_PAYMENT_PCKREDITOR_DE_MONTH),
            'monthfees' => explode(";", MODULE_PAYMENT_PCKREDITOR_DE_MONTH_FEE),
            'startfees' => explode(";", MODULE_PAYMENT_PCKREDITOR_DE_START_FEE),
            'rates' => explode(";", MODULE_PAYMENT_PCKREDITOR_DE_RATE));

        for ($i = 0 ; $i < sizeof($pclassArr['pclass']); $i++) {
            if ($pclass == $pclassArr['pclass'][$i]) {
                $months = $pclassArr['months'][$i];
                $monthfee = $pclassArr['monthfees'][$i] * 100;
                $startfee = $pclassArr['startfees'][$i] * 100;
                $rate = $pclassArr['rates'][$i];
                break;
            } 
        } 
        // Make sure we have a float regardless of  separator
        $rate = ereg_replace("(^[0-9]*)(\\.|,)([0-9]*)(.*)", "\\1.\\3", $rate);
        if (!is_numeric($rate)) $rate = ereg_replace("(^[0-9]*)(.*)", "\\1", $rate);
        if (!is_numeric($rate)) $rate = 0;
        $rate = ((float) $rate) * 100;
        $dailyrate = daily_rate($rate);
        $monthpayment = calc_monthpayment($sum + $startfee, $dailyrate, $months);
        $result = round($monthpayment + $monthfee);

        return 0;
    } 

    function install()
    {
        global $db;
        $extraString = '<b>Click <a href="?set=payment&module=pckreditor_de&get_pclasses=true">here</a> to update your pclasses</b><br><br>';
		$db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('" . $extraString . "Enable Klarna Module', 'MODULE_PAYMENT_PCKREDITOR_DE_STATUS', 'True', 'Do you want to accept Klarna payments?', '6', '0', 'zen_cfg_select_option(array(\'True\', \'False\'), ', now())");
        
        $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, use_function, set_function, date_added) values ('Payment Zone', 'MODULE_PAYMENT_PCKREDITOR_DE_ZONE', '0', 'If a zone is selected, only enable this payment method for that zone.', '6', '2', 'zen_get_zone_class_title', 'zen_cfg_pull_down_zone_classes(', now())");
        
        $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Merchant ID', 'MODULE_PAYMENT_PCKREDITOR_DE_EID', '0', 'Merchant ID (estore id) to use for the Klarna service (provided by Klarna)', '6', '0', now())");
        
        $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Shared secret', 'MODULE_PAYMENT_PCKREDITOR_DE_SECRET', '', 'Shared secret to use with the Klarna service (provided by Klarna)', '6', '0', now())");
        
        $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Enable Auto Activate', 'MODULE_PAYMENT_PCKREDITOR_DE_AUTO_ACTIVATE', 'False', 'Do you want to enable invoice auto activate?', '6', '0', 'zen_cfg_select_option(array(\'True\', \'False\'), ', now())");
        
        $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Activate delay (days)', 'MODULE_PAYMENT_PCKREDITOR_DE_AUTO_ACTIVATE_SEND_DELAY', '0', 'When auto activating delay sending the invoice for x days.', '6', '2', now())");
        
        $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Product artno attribute (id or model)', 'MODULE_PAYMENT_PCKREDITOR_DE_ARTNO', 'id', 'Use the following product attribute for ArtNo.', '6', '2', 'zen_cfg_select_option(array(\'id\', \'model\'),', now())");
        
        $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Pre-populate Personnummer field', 'MODULE_PAYMENT_PCKREDITOR_DE_PRE_POPULATE', 'True', 'Do you want to pre-populate the personnummer field?', '6', '0', 'zen_cfg_select_option(array(\'True\', \'False\'), ', now())");
        
        $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Ignore table', 'MODULE_PAYMENT_PCKREDITOR_DE_ORDER_TOTAL_IGNORE', 'ot_tax,ot_total,ot_subtotal,ot_shipping', 'Ignore these entries from order total list when compiling the invoice data', '6', '2', now())");
        
        $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Credit limit', 'MODULE_PAYMENT_PCKREDITOR_DE_ORDER_LIMIT', '10000', 'Only show this payment alternative for orders less than the value below.', '6', '2', now())");
        
        $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Sort order of display.', 'MODULE_PAYMENT_PCKREDITOR_DE_SORT_ORDER', '37', 'Sort order of display. Lowest is displayed first.', '6', '0', now())");
        
        $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, use_function, date_added) values ('Set Order Status', 'MODULE_PAYMENT_PCKREDITOR_DE_ORDER_STATUS_ID', '0', 'Set the status of orders made with this payment module to this value', '6', '0', 'zen_cfg_pull_down_order_statuses(', 'zen_get_order_status_name', now())");
        
        $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, use_function, set_function, date_added) values ('Tax Class', 'MODULE_PAYMENT_PCKREDITOR_DE_TAX_CLASS', '0', 'Use the following tax class on the payment charge.', '6', '6', 'zen_get_tax_class_title', 'zen_cfg_pull_down_tax_classes(', now())");
        
        $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Set Pclass ID', 'MODULE_PAYMENT_PCKREDITOR_DE_PCLASS', '210;211;212', 'Semicolon separated list, with no spaces.', '6', '7', now())");
        
        $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Set Month', 'MODULE_PAYMENT_PCKREDITOR_DE_MONTH', '6;12;36', 'Semicolon separated list, with no spaces.', '6', '8', now())");
        
        $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Set Monthly Fee', 'MODULE_PAYMENT_PCKREDITOR_DE_MONTH_FEE', '3.95;3.95;3.95', 'Semicolon separated list, with no spaces.', '6', '8', now())");
        
        $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Set Rate', 'MODULE_PAYMENT_PCKREDITOR_DE_RATE', '0;0;14.95', 'Semicolon separated list, with no spaces.', '6', '9', now())");
        
        $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Set Start Fee', 'MODULE_PAYMENT_PCKREDITOR_DE_START_FEE', '29.95;39.95;29.95', 'Semicolon separated list, with no spaces.', '6', '10', now())");
		
		$db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Pclass for Account', 'MODULE_PAYMENT_PCKREDITOR_DE_PCLASS_DEFAULT', '0', 'Pclass for \"Account\"', '6', '10', now())");
    
    } 

    function remove()
    {
        global $db;
        $db->Execute("delete from " . TABLE_CONFIGURATION . " where configuration_key in ('" . implode("', '", $this->keys()) . "')");
    } 

    function keys()
    {
		$filename = explode('?', basename($_SERVER['REQUEST_URI'], 0));//[0];
  	
		if ($filename[0] == "modules.php"){
			if ($_GET['get_pclasses'] == TRUE)  {
				require_once ("../". DIR_WS_CLASSES . 'kreditor.php');
				global $db;
				$eid = MODULE_PAYMENT_PCKREDITOR_DE_EID;
				$secret = MODULE_PAYMENT_PCKREDITOR_DE_SECRET;
				fetch_pclasses($eid, $KRED_EUR, $secret, $KRED_ISO3166_DE, $KRED_ISO639_DE, $result);
						
				$pclassIDs = "";
				$pclassMonths = "";
				$pclassRates = "";
				$pclassFees = "";
				$pclassStartfees = "";
				
				foreach ($result as $pclass) {
					if (strtolower($pclass[1]) == "1/24 avbetalningskonto" || strtolower($pclass[1]) == "konto") {
						$db->Execute("update " . TABLE_CONFIGURATION . " set configuration_value = '" . $pclass[0] . "' where configuration_key = 'MODULE_PAYMENT_PCKREDITOR_DE_PCLASS_DEFAULT'");
		
					} else {
						$pclassIDS .= "$pclass[0];";
						$pclassFees.= $pclass[4]/100 . ";";
						$pclassMonths .= "$pclass[2];";
						$pclassRates .= ($pclass[5]/100) . ";";
						$pclassStartfees .= ($pclass[3]/100) . ";";
					}
				}
				
				$pclassIDS = substr($pclassIDS,0,-1);
				$pclassMonths = substr($pclassMonths,0,-1);
				$pclassFees = substr($pclassFees,0,-1);
				$pclassRates = substr($pclassRates,0,-1);
				$pclassStartfees = substr($pclassStartfees,0,-1);

		
		
				$db->Execute("update " . TABLE_CONFIGURATION . " set configuration_value = '" . $pclassIDS . "' where configuration_key = 'MODULE_PAYMENT_PCKREDITOR_DE_PCLASS'");
				$db->Execute("update " . TABLE_CONFIGURATION . " set configuration_value = '" . $pclassMonths . "' where configuration_key = 'MODULE_PAYMENT_PCKREDITOR_DE_MONTH'");
				$db->Execute("update " . TABLE_CONFIGURATION . " set configuration_value = '" . $pclassRates . "' where configuration_key = 'MODULE_PAYMENT_PCKREDITOR_DE_RATE'");
				$db->Execute("update " . TABLE_CONFIGURATION . " set configuration_value = '" . $pclassFees . "' where configuration_key = 'MODULE_PAYMENT_PCKREDITOR_DE_MONTH_FEE'");
				$db->Execute("update " . TABLE_CONFIGURATION . " set configuration_value = '" . $pclassStartfees . "' where configuration_key = 'MODULE_PAYMENT_PCKREDITOR_DE_START_FEE'");
		
		
			} else if ($_GET['view_pclasses'] == TRUE)  {
				$query = tep_db_query("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_PAYMENT_PCKREDITOR_PCLASS'");
				$arr = tep_db_fetch_array($query);
				tep_db_query("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_PAYMENT_PCKREDITOR_MONTH'");
				tep_db_query("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_PAYMENT_PCKREDITOR_RATE'");
				tep_db_query("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_PAYMENT_PCKREDITOR_START_FEE'");
				print_r($arr);
			}
		}
        return array('MODULE_PAYMENT_PCKREDITOR_DE_STATUS',
            'MODULE_PAYMENT_PCKREDITOR_DE_ORDER_STATUS_ID',
            'MODULE_PAYMENT_PCKREDITOR_DE_EID',
            'MODULE_PAYMENT_PCKREDITOR_DE_SECRET',
            'MODULE_PAYMENT_PCKREDITOR_DE_ARTNO',
            'MODULE_PAYMENT_PCKREDITOR_DE_AUTO_ACTIVATE',
            'MODULE_PAYMENT_PCKREDITOR_DE_AUTO_ACTIVATE_SEND_DELAY',
            'MODULE_PAYMENT_PCKREDITOR_DE_PRE_POPULATE',
            'MODULE_PAYMENT_PCKREDITOR_DE_ORDER_LIMIT',
            'MODULE_PAYMENT_PCKREDITOR_DE_ORDER_TOTAL_IGNORE',
            'MODULE_PAYMENT_PCKREDITOR_DE_ZONE',
            'MODULE_PAYMENT_PCKREDITOR_DE_TAX_CLASS',
            'MODULE_PAYMENT_PCKREDITOR_DE_SORT_ORDER',
            'MODULE_PAYMENT_PCKREDITOR_DE_PCLASS',
            'MODULE_PAYMENT_PCKREDITOR_DE_MONTH',
            'MODULE_PAYMENT_PCKREDITOR_DE_MONTH_FEE',
            'MODULE_PAYMENT_PCKREDITOR_DE_RATE',
            'MODULE_PAYMENT_PCKREDITOR_DE_START_FEE',
			'MODULE_PAYMENT_PCKREDITOR_DE_PCLASS_DEFAULT');
    } 
} 

?>
